<template>
  <q-btn v-if="showLog" :icon="mdiShieldBugOutline" flat round @click="dialog = true">
    <q-badge color="red" floating> {{ logStore.errorLogs.length }}</q-badge>
  </q-btn>

  <q-dialog v-model="dialog">
    <q-card style="width: 700px">
      <q-toolbar> <q-toolbar-title>查看错误日志</q-toolbar-title> <q-btn v-close-popup icon="close" round flat /> </q-toolbar>

      <q-card-section style="padding: 0 5px; max-height: 600px; overflow-y: auto">
        <q-list separator bordered>
          <q-item v-for="(log, index) in logStore.errorLogs" :key="index" class="q-px-sm q-py-md">
            <q-item-section style="max-width: 10px">
              {{ index + 1 }}
            </q-item-section>
            <q-item-section>
              <q-item-label class="text-green"> {{ 'URL：' + log.url }} </q-item-label>
              <q-item-label class="text-primary"> {{ 'ERR：' + log.err.message + '；' + log.info }} </q-item-label>
              <q-item-label overline>
                <q-input :model-value="log.err.stack ?? ''" type="textarea" readonly rows="5" @click="copy(log.err.stack ?? '')">
                  <q-tooltip v-if="log.err.stack ?? ''" anchor="top middle"> 点击复制 </q-tooltip>
                </q-input>
              </q-item-label>
            </q-item-section>
          </q-item>
        </q-list>
      </q-card-section>

      <q-card-actions>
        <q-space />
        <q-btn v-close-popup>关闭</q-btn>
        <q-btn color="error" icon="save" @click="clearErrorLogs">清空</q-btn>
      </q-card-actions>
    </q-card>
  </q-dialog>
</template>

<script setup lang="ts">
  import { computed, ref } from 'vue';
  import { copyToClipboard } from 'quasar';
  import { mdiShieldBugOutline } from '@quasar/extras/mdi-v7';

  import { Message } from 'src/utils';
  import { useAppStore } from 'src/stores';

  const dialog = ref(false);
  const logStore = useAppStore();
  const showLog = computed(() => logStore.errorLogs.length > 0);

  function clearErrorLogs() {
    logStore.clearErrorLogs();
    Message.success('操作成功');
    dialog.value = false;
  }

  function copy(text: string) {
    if (!text || text.trim() === '') {
      return;
    }
    copyToClipboard(text)
      .then(() => Message.success('已成功复制到剪贴板'))
      .catch(() => Message.error('操作失败，可能是浏览器不支持'));
  }
</script>
